import { getOssPrivateAssetUrl } from "@/utils/useOss";

// 获取音频时长计时字符串
export const audioDurationTimeStr = (duration: number): String => {
  const minute = Math.floor(duration / 60);
  const second = Math.floor(duration % 60);
  const minuteStr = minute < 10 ? `0${minute}` : `${minute}`;
  const secondStr = second < 10 ? `0${second}` : `${second}`;
  return `${minuteStr}:${secondStr}`;
};

// 获取音频时长字符串
export const audioDurationStr = (duration: number): String => {
  const minute = Math.floor(duration / 60);
  const second = duration % 60;
  const minuteStr = minute < 10 ? `0${minute}'` : `${minute}"`;
  const secondStr = second < 10 ? `0${second}'` : `${second}"`;
  if (duration < 60) {
    return secondStr;
  }
  return `${minuteStr}:${secondStr}`;
};

// 生成随机的UUID
export const generateUUID = () => {
  var result, i, j;
  result = "";
  for (j = 0; j < 32; j++) {
    if (j == 8 || j == 12 || j == 16 || j == 20) result = result + "-";
    i = Math.floor(Math.random() * 16)
      .toString(16)
      .toUpperCase();
    result = result + (Math.random() < 0.5 ? "0" : "1") + i;
  }
  return result;
};

// 获取文件url
export const getFileUrl = (url: string) => {
  if (url && url.startsWith("http")) {
    return url;
  } else {
    return getOssPrivateAssetUrl(url);
  }
};

export const buildUUID = () => {
  const hexList = [];
  for (let i = 0; i <= 15; i++) {
    hexList[i] = i.toString(16);
  }
  let uuid = "";
  for (let i = 1; i <= 36; i++) {
    if (i === 9 || i === 14 || i === 19 || i === 24) {
      uuid += "-";
    } else if (i === 15) {
      uuid += 4;
    } else if (i === 20) {
      uuid += hexList[(Math.random() * 4) | 8];
    } else {
      uuid += hexList[(Math.random() * 16) | 0];
    }
  }
  return uuid.replace(/-/g, "");
};

// 跳转到登录页
export const jumpLoginPage = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const path = currentPage.route;
  if (
    path === "pagesA/login/index" ||
    path === "pagesA/agreement/privacy" ||
    path === "pagesA/agreement/user"
  ) {
    return;
  }
  uni.navigateTo({
    url: "/pagesA/login/index",
  });
};

export const isJSON = (str: string) => {
  if (typeof str == "string") {
    try {
      JSON.parse(str);
      return true;
    } catch (e) {
      return false;
    }
  }
};
